/*
 * Zenlayer.com Inc.
 * Copyright (c) 2014-2021 All Rights Reserved.
 */

//import com.google.common.util.concurrent.ThreadFactoryBuilder;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author wolfgang
 * @date 2021-06-03 14:29:39
 * @version $ Id: ConcurrentUtils.java, v 0.1  wolfgang Exp $
 */
public class ConcurrentUtils {
    static ThreadFactory   namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("current-pool-%d").build();
    static ExecutorService executorService    = new ThreadPoolExecutor(5, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024),
            namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());

    public static Concurrent allocate() {
        return new Concurrent();
    }

    public static class Concurrent {

        List<Future<?>> futures = new ArrayList<>();

        public <T> void invoke(Runnable runnable) {
            Future<?> future = executorService.submit(runnable);
            futures.add(future);
        }

        public void waitAllDone() {
            System.out.println("---------");
            try {
                for (Future<?> future : futures) {
                    future.get();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        ConcurrentUtils.allocate().invoke(()->{
            System.out.println("起飞");
        });

        ConcurrentUtils.allocate().invoke(()->{
            System.out.println("哈哈哈");
        });

    }
}
